﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace RemoteDesktop
{
    class Context
    {
        private static Context mInstance;
        public string IpAddress { get; set; }
        public string IpAddressPort { get; set; }
        public string IpAddressRole { get; set; }
        public string ServerIpAddress1 { get; set; }
        public string ServerIpAddress1Port { get; set; }
        public string ServerIpAddress1Role { get; set; }
        public string RoleType { get; set; }

        private Dictionary<string, ConnectInfo> dics = new Dictionary<string, ConnectInfo>();
        private Context(){
        }
        public static Context Get()
        {
            if (mInstance == null)
            {
                mInstance = new Context();
            }
            return mInstance;
        }
        public void SetConnectInfo(string ip,ConnectInfo info)
        {
            if(ip!="" && info != null && !dics.ContainsKey(ip))
            {
                dics.Add(ip, info);
            }
        }
        public ConnectInfo GetConnectInfo(string ip)
        {
            ConnectInfo info = null;
            if (ip != "")
            {
                dics.TryGetValue(ip, out info);
            }
            return info;
        }
        public byte[] Serialize<T>(T obj)
        {
            if (obj == null)
            {
                return null;
            }

            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, obj);
                return stream.ToArray();
            }
        }
        public T Deserialize<T>(byte[] bytes)
        {
            if (bytes == null)
            {
                return default(T);
            }

            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}
